package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

   @Autowired
   FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.endpoint}")
    String endpoint;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //参数合法性校验
        if (multipartFile==null || multipartFile.getSize()==0){
            CustException.cust(AppHttpCodeEnum.FILE_UPLOAD_PARAMREQUIRE_ERROR);
        }

        //获取文件名
        String filename= UUID.randomUUID().toString().replace("-","");
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //****************************文件上传到阿里云********************
        String fileId=null;

        try {
            fileId=fileStorageService.store(prefix,filename+postfix,multipartFile.getInputStream());
            log.info("fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl uploadPicture error: {}",e);
            CustException.cust(AppHttpCodeEnum.FILE_UPLOAD_PARAMREQUIRE_ERROR);
        }
        //***************************文件上传结束*****************

        //封装数据并保持到素材库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(fileId);// 保存到数据库的文件路径
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmMaterial.setUserId(user.getId());

        save(wmMaterial);
        wmMaterial.setUrl(webSite+fileId);//响应给前端时的文件路径
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //参数校验
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> wrapper=new LambdaQueryWrapper<>();
        //查询收藏
        if (dto.getIsCollection()!=null&& dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId,user.getId());

        //按时间倒序查询
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //分页查询
        IPage<WmMaterial> pageParam=new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial>pageResult=page(pageParam,wrapper);
        //给图片路径加上网点前缀
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        PageResponseResult result=new PageResponseResult(
                dto.getPage(),
                dto.getSize(),
                (int) pageResult.getTotal(),
                pageResult.getRecords()
        );

        return result;
    }

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        //检查参数合法性
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        /**
         * 业务处理
         * 判断是否存在图片
         * 判断id是否被引用，不能删除被引用图片
         * 不被引用则在阿里云删除图片，素材库数据库中移除
         */
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer count = wmNewsMaterialMapper.selectCount(
                Wrappers.<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getMaterialId, id)
        );
        if (count>0){
            CustException.cust(AppHttpCodeEnum.FILE_DELETE_ERROR);
        }

        //从阿里云端删除图片从数据库删除记录
        fileStorageService.delete(wmMaterial.getUrl());
        removeById(id);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //参数检查
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //更新状态
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(
                Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,uid)
        );

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
